package com.frinder.base.advisor;

import com.frinder.base.global.Result;
import com.frinder.base.global.ResultGenerator;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author frinder
 * @date 2018/6/14
 * @Description: 核验失败统一处理器
 */
@Order(1)
@ControllerAdvice
public class ValidateControllerAdvice {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Result validExceptionHandler(MethodArgumentNotValidException ex) {
        List<String> errorList = ex
                .getBindingResult()
                .getFieldErrors()
                .stream()
                .map(e -> String.format("%s:%s", e.getField(), e.getDefaultMessage()))
                .collect(Collectors.toList());
        String message = Joiner.on(";").join(errorList);
        logger.error("核验失败：{}", message);
        return ResultGenerator.genFailResult(message);
    }

}
